package com.jwdf.uda.ui.fragment.user.register;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentBindMobileBinding;
import com.jwdf.uda.event.UserEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.RegisterStep1Action;
import com.jwdf.uda.ui.activity.H5Activity;
import com.jwdf.uda.ui.activity.MainLoginEntryActivity;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.BroadcastUtils;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.StringUtils;
import com.jwdf.uda.utils.ToastUtils;
import com.jwdf.uda.utils.UdaUtils;
import com.jwdf.uda.view.dialog.ConfirmDialog;

import retrofit2.Response;

/**
 * Created by Administrator on 2016/5/24.
 */
public class BindMobileFragment extends BaseFragment {
    private FragmentBindMobileBinding mDataBinding;
    public View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(R.id.btn_auth_code == v.getId()) {
                mDataBinding.ivClearInput.setVisibility(View.GONE);
                UdaUtils.hideInputMethod(getContext(), mDataBinding.inputEdit);
                String mobile = mDataBinding.inputEdit.getText().toString().trim();
                if(TextUtils.isEmpty(mobile)) {
                    ToastUtils.show(getContext(), getString(R.string.mobile_can_not_be_null));
                    return;
                }
                if(!UdaUtils.isMobile(mobile)) {
                    ToastUtils.show(getContext(), getString(R.string.please_correct_the_mobile));
                    return;
                }
                authMobieCode(mobile);
            } else if(R.id.iv_clear_input == v.getId()) {
                mDataBinding.inputEdit.setText("");
            }
        }
    };
    private BroadcastReceiver mBroadcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(BroadcastUtils.MOBILE_ALREADY_REGISTER.equals(intent.getAction())) {
                showAlertDialog();
            }
        }
    };
    private TextWatcher mTextChangeListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //mDataBinding.inputEdit.setSelection(s.length());
        }

        @Override
        public void afterTextChanged(Editable s) {
            mDataBinding.ivClearInput.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDataBinding = FragmentBindMobileBinding.inflate(inflater, container, false);
        mDataBinding.setBindMobileFragment(this);
        initViews();
        return mDataBinding.getRoot();
    }
    private void initViews() {
        BroadcastUtils.registerMobileOccupyBroadcast(getContext(), mBroadcast);
        mDataBinding.inputEdit.addTextChangedListener(mTextChangeListener);
        mDataBinding.ivClearInput.setOnClickListener(mClickListener);
        mDataBinding.tvProtocol.setPaintFlags(mDataBinding.tvProtocol.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        mDataBinding.tvProtocol.setMovementMethod(LinkMovementMethod.getInstance());
        mDataBinding.tvProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = ConfigUtils.getUserProtocol(v.getContext());
                StringBuilder stringBuilder = new StringBuilder("http://");
                if (url.contains("http")) {
                    H5Activity.start(v.getContext(), url);
                } else {
                    H5Activity.start(v.getContext(), stringBuilder.append(url).toString());
                }
            }
        });
    }
    @Override
    public void onDestroyView() {
        BroadcastUtils.unregisterReceiver(getContext(), mBroadcast);
        super.onDestroyView();
    }
    private void showAlertDialog() {
        ConfirmDialog dlg = new ConfirmDialog(getContext(), getString(R.string.dialog_register_title),getString(R.string.dialog_toast_mobile_occupy), getString(R.string.dialog_switch_mobile), getString(R.string.dialog_go_login), new ConfirmDialog.CallbackListener() {
            @Override
            public void clickNo() {
                mDataBinding.inputEdit.setText("");
            }

            @Override
            public void clickYes() {
                UserEvent event = new UserEvent();
                event.setEvent(UserEvent.EVENT_GO_LOGIN);
                EventBusUtil.post(event);
                MainLoginEntryActivity.start(getContext(), StringUtils.filterNullAndTrim(mDataBinding.inputEdit.getText().toString()));
                getActivity().finish();
            }
        });
        dlg.show();
    }
    private void authMobieCode(final String mobile) {
        showProgressDialog();
        onNewRequestCall(RegisterStep1Action.newInstance(getContext(), mobile).request(new AHttpService.IResCallback<PbBean.PbResUserRegisterStep1>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserRegisterStep1> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    UserEvent event = new UserEvent();
                    event.setEvent(UserEvent.EVENT_STEP_1);
                    event.setExtra(mobile);
                    EventBusUtil.post(event);
                }
            }
        }));
    }
}
